import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../models/message_list_entity.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class MessageLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  late int unreadCount;

  var isLoading = true.obs;
  var bottomTips = ''.obs;
  var messageList = <MessageData>[].obs;

  var tabTitles = ['全部', '收入支出', '审批结果', '待办事项'].obs;

  final scrollController = ScrollController();
  late TabController tabController;

  final pageSize = 20;
  int _page = 1;
  int _type = 0;

  @override
  void onInit() {
    super.onInit();

    unreadCount = Get.arguments;

    tabController = TabController(length: tabTitles.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        _type = tabController.index;
        _page = 1;
        messageList.clear();
        _getMessageList();
      }
    });

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getMessageList();
      }
    });

    _getMessageList();
  }

  void _getMessageList() {
    apiService.getMessageList(_page, pageSize, _type).then((value) => {
          isLoading.value = false,
          _page++,
          if (value != null)
            {
              messageList.addAll(value.data),
              if (value.data.length != pageSize)
                {bottomTips.value = noMoreTip}
              else
                {bottomTips.value = loadingTip}
            }
          else
            {bottomTips.value = noMoreTip},
          _readMessage(),
        });
  }

  void _readMessage() {
    apiService.messageRead(commonService.getRole()).then((value) => {
          if (value != null) {unreadCount = 0}
        });
  }
}
